<template>
  <p v-text="text" ref="p"></p>
</template>

<script>
import { getStyle } from '@/common/js/dom'
import { debounce } from '@/common/js/util'
export default {
  name: 'breviary',
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  mounted() {
    const p = this.$refs.p
    this.sliceText(p)
    window.addEventListener('resize', debounce(() => {
      p.textContent = this.text
      this.sliceText(p)
    }, 2000))
  },
  methods: {
    sliceText(el) {
      // console.log(el)
      // console.log('textContent', el.textContent)
      // console.log('clientHeight', el.clientHeight)
      // console.log('offsetHeight', el.offsetHeight)
      // console.log('scrollHeight', el.scrollHeight)
      // console.log('style', getStyle(el, 'font-size'))
      if (el.scrollHeight <= el.offsetHeight | !el.textContent) {
        return el.textContent
      }

      const chatWidth = parseInt(getStyle(el, 'font-size').match(/^(\d+)px$/)[1])
      const sliceNum = el.offsetWidth / chatWidth | 0
      el.textContent = el.textContent.slice(0, -sliceNum) + '...'
      this.sliceText(el)
    }
  },
  computed: {
  },
  watch: {
    text(newY) {
      this.$nextTick(() => {
        this.sliceText(this.$refs.p)
      })
    }
  }
}
</script>

<style>

</style>
